
lunovns = {}

local floor_pos = function(pos)
	return {x=math.floor(pos.x),y=math.floor(pos.y),z=math.floor(pos.z)}
end

local UFO_SPEED = 0.8 --Padrão = 1.0 (Aceleração)
local UFO_TURN_SPEED = 3.0 --Padrão = 2.0 (Velocidade de Giro)
local UFO_MAX_SPEED = 20 --Padrão = 10.0 (Velocidad Maxima)
local UFO_FUEL_USE = 0.005 --Padrão = 0.01 (Consumo de Combustivel)
local UFO_LEVEL_MIN = 4 --Padrão = 5 (Nivel minimo para pilotar)

lunovns.fuel_from_wear = function(wear)
	local fuel
	if wear == 0 then
		fuel = 0
	else
		fuel = (65535-(wear-1))*100/65535
	end
	return fuel
end

lunovns.wear_from_fuel = function(fuel)
	local wear = (100-(fuel))*65535/100+1
	if wear > 65535 then wear = 0 end
	return wear
end

lunovns.get_fuel = function(self)
	return self.fuel
end

lunovns.set_fuel = function(self,fuel,object)
	self.fuel = fuel
end

lunovns.ufo_to_item = function(self)
	local wear = lunovns.wear_from_fuel(lunovns.get_fuel(self))
	return {name="lunovns:ufo",wear=wear}
end

lunovns.ufo_from_item = function(itemstack,placer,pointed_thing)
	-- set owner
	lunovns.next_owner = placer:get_player_name()
	-- restore the fuel inside the item
	local wear = itemstack:get_wear()
	lunovns.set_fuel(lunovns.ufo,lunovns.fuel_from_wear(wear))
	-- add the entity
	local disco = minetest.env:add_entity(pointed_thing.above, "lunovns:ufo")
	disco:setyaw(placer:get_look_yaw() - math.pi / 2) -- Se o mesmo que => disco:get_luaentity().object:setyaw(placer:get_look_yaw() - math.pi / 2)
	-- remove the item
	itemstack:take_item()
	-- reset owner for next ufo
	lunovns.next_owner = ""
end

lunovns.check_owner = function(self, clicker)
	if self.owner_name ~= "" and clicker:get_player_name() ~= self.owner_name then
		return false
	elseif self.owner_name == "" then
		self.owner_name = clicker:get_player_name()
	end
	return true
end

lunovns.getDetachedInventory = function(self, player)
	local inv = minetest.create_detached_inventory("trunk_"..player:get_player_name(), { --trunk
	--local inv =  minetest.create_detached_inventory("trunk", { --trunk
		-- allow_* - return value is the number of items allowed to move, or -1 to copy the stack instead of move

		-- Called when a player wants to move items inside the inventory
		allow_move = function(inv, from_list, from_index, to_list, to_index, count, player) 
			return count
		end,

		-- Called when a player wants to put items into the inventory
		allow_put = function(inv, listname, index, stack, player) 
			return stack:get_count()
		end,

		-- Called when a player wants to take items out of the inventory
		allow_take = function(inv, listname, index, stack, player) 
			return stack:get_count()
		end,

		-- on_* - no return value
		-- Called after the actual action has happened, according to what was allowed.
		on_move = function(inv, from_list, from_index, to_list, to_index, count, player) end,
		on_put = function(inv, listname, index, stack, player) 
			--print("================================ PUT ===="..dump(inv))

			print(player:get_player_name().." colocou "..stack:get_count().." '"..stack:get_name().."' no porta-malas do seu disco-voador!")
			self.invTrunk[player:get_player_name()] = inv:get_list("main")
			
			
			--print(player:get_player_name().." colocou um item no porta-malas do seu disco-voador; listname="..dump(listname)..", index="..dump(index)..", stack="..dump(stack))
			--if stack then
				--print("stack:get_name()="..dump(stack:get_name())..", stack:get_count()="..dump(stack:get_count()))
			--end



			--local stack2 = ItemStack(stack:get_name().." ".. stack:get_count())
			--inv:add_item("main", stack2)
			--inv:get_width("main")
			

		end,
		on_take = function(inv, listname, index, stack, player) 
			print(player:get_player_name().." retirou "..stack:get_count().." '"..stack:get_name().."' no porta-malas do seu disco-voador!")
			self.invTrunk[player:get_player_name()] = inv:get_list("main")
			--print("================================ TAKE ==="..dump(inv))
			--print(player:get_player_name().." {PUT} um item do {detached:trunk_"..player:get_player_name().."}; listname="..dump(listname)..", index="..dump(index)..", stack="..dump(stack))
         --if stack then
         --    print("stack:get_name()="..dump(stack:get_name())..", stack:get_count()="..dump(stack:get_count()))
         --end
		end,
	})
	--inv:set_size("main", 8*4)
	if self.invTrunk[player:get_player_name()]~=nil then
		--inv = self.invTrunk
		inv:set_list("main", self.invTrunk[player:get_player_name()])
	else
		inv:set_size("main", 8*4)
	end
	
	return inv
end

lunovns.next_owner = ""
lunovns.ufo = {
	physical = true,
	collisionbox = {-1.5,-0.5,-1.5	 ,1.5,1.0,1.5}, --Padrão = {-1.5,-0.5,-1.5, 1.5,2.0,1.5}
	visual = "mesh",
	mesh = "ufo.x",
	textures = {"ufo_0.png"},
	driver = nil,
	owner_name = "",
	v = 0,
	fuel = 0,
	fueli = 0,
	soundHandle=nil,
	invTrunk={ }
}

function lunovns.ufo:on_rightclick (clicker)
	if not clicker or not clicker:is_player() then
		return
	end
	
	if self.driver and clicker == self.driver then
		self.driver = nil
		clicker:set_detach()
		if self.soundHandle~=nil then minetest.sound_stop(self.soundHandle) end
	elseif not self.driver then
		local Xp = lunomods.getCharValue(clicker:get_player_name(), "Experience")
		if Xp==nil or Xp=="" or type(Xp)~="number" or (type(Xp)=="number" and Xp<0) then 
			Xp=0 
		else
			Xp = math.floor(Xp)
		end
		local Nv = math.floor(1 + math.sqrt(Xp/100)) --Nv == Nível
		if Nv<UFO_LEVEL_MIN then
			minetest.chat_send_player(clicker:get_player_name(), "[DISCO-VOADOR] E preciso ter nivel "..UFO_LEVEL_MIN.." para pilotar este veiculo!")
			minetest.sound_play("sfx_falha", {object = self.object, gain = 2.0, max_hear_distance = 10}) --toca som "sfx_falha".ogg a distancia de 10 blocos do elicoptero.
			return
		end
	
		if lunovns.check_owner(self,clicker) then
			self.driver = clicker
			clicker:setpos(self.object:getpos()) --Esta linha e necessaria para que o player fique bem alinhado com a cadeira antes de ser atachado ao veiculo.
			clicker:set_attach(self.object, "", {x=0,y=7.5,z=0}, {x=0,y=0,z=0}) --  <== Linha Original
			--clicker:set_attach(self.object, "Root", {x=0,y=7.5,z=0}, {x=0,y=0,z=0}) --  <== Linha poroposta ("Root" deixa o player deitado embaixo na nave)
			self.soundHandle=minetest.sound_play({name="sfx_ufo"},{object = self.object, gain = 0.5, max_hear_distance = 32, loop = true,})
			--minetest.chat_send_player(clicker:get_player_name(), "[DISCO-VOADOR] Bom retorno, "..self.owner_name.."!") --Mensgem desnecessaria!
		else
			minetest.chat_send_player(clicker:get_player_name(), "[DISCO-VOADOR] Este veiculo pertece a '"..self.owner_name.."' !")
			minetest.sound_play("sfx_falha", {object = self.object, gain = 2.0, max_hear_distance = 10}) --toca som "sfx_falha".ogg a distancia de 10 blocos do elicoptero.
		end
	end
end

function lunovns.ufo:on_activate (staticdata, dtime_s)
	if lunovns.next_owner ~= "" then
		self.owner_name = lunovns.next_owner
		lunovns.next_owner = ""
	else
		local data = staticdata:split(';')
		if data and data[1] and data[2] then
			self.owner_name = data[1]
			self.fuel = tonumber(data[2])
		end
	end
	self.object:set_armor_groups({immortal=1})
end

function lunovns.ufo:on_punch (puncher, time_from_last_punch, tool_capabilities, direction)
	if puncher and puncher:is_player() then
		if lunovns.check_owner(self,puncher) then
			if not self.driver then
				local inv = lunovns.getDetachedInventory(self, puncher)
				--[[
				if self.invTrunk[puncher:get_player_name()]~=nil then
					--inv = self.invTrunk
					inv:set_list("main", self.invTrunk[puncher:get_player_name()])
				else
					inv:set_size("main", 8*4)
				end
				]]--

				if inv:is_empty("main") then
					if self.soundHandle~=nil then minetest.sound_stop(self.soundHandle) end
					puncher:get_inventory():add_item("main", lunovns.ufo_to_item(self)) --Transforma a Nave em um item
					self.object:remove() --Remove a instacia da nava do mapa.
				else
					minetest.sound_play("sfx_falha", {object = self.object, gain = 2.0, max_hear_distance = 10}) --toca som "sfx_falha".ogg a distancia de 10 blocos do elicoptero.
					minetest.chat_send_player(puncher:get_player_name(), "[DISCO-VOADOR] Nao e possivel encolher o este veiculo antes de esvaziar seu porta-malas!")
				end
			else
				minetest.sound_play("sfx_falha", {object = self.object, gain = 2.0, max_hear_distance = 10}) --toca som "sfx_falha".ogg a distancia de 10 blocos do elicoptero.
				minetest.chat_send_player(puncher:get_player_name(), "[DISCO-VOADOR] Nao e possivel encolher o este veiculo antes do piloto de sair de dentro!")
			end
		else
			minetest.sound_play("sfx_falha", {object = self.object, gain = 2.0, max_hear_distance = 10}) --toca som "sfx_falha".ogg a distancia de 10 blocos do elicoptero.
			minetest.chat_send_player(puncher:get_player_name(), "[DISCO-VOADOR] Este veiculo pertece a '"..self.owner_name.."' !")
		end
	end
end


function lunovns.ufo:getFormSpecTrunk(player)
	return "size[8,9.5]"
	..default.gui_bg
	..default.gui_bg_img
	..default.gui_slots
	.."label[3,0; PORTA-MALAS]"
	.."list[detached:trunk_"..player:get_player_name()..";main;0,0.6;8,4;]"
	--.."list[detached:trunk;main;0,0.6;8,4;]"
	.."button[3.2,4.5;2,1;btnDownload;Descarregar]"
	.."list[current_player;main;0,5.5;8,1;]"
	.."list[current_player;main;0,6.7;8,3;8]"
	--.."list[current_player;main;0,4.85;8,1;]"
	--.."list[current_player;main;0,6.08;8,3;8]"
	..default.get_hotbar_bg(0,5.5)
end

function lunovns.ufo:on_step (dtime)
	local fuel = lunovns.get_fuel(self)
	if self.driver then
		self.driver:set_breath(20)
		
		local ctrl = self.driver:get_player_control()
		local vel = self.object:getvelocity()
		if fuel == nil then fuel = 0 end

		if fuel > 0 and ctrl.left then -- Girar a esquerda
			self.object:setyaw(self.object:getyaw()+math.pi/120*UFO_TURN_SPEED)
			fuel = fuel - UFO_FUEL_USE
		end
		if fuel > 0 and ctrl.right then -- Girar a esquerda
			self.object:setyaw(self.object:getyaw()-math.pi/120*UFO_TURN_SPEED)
			fuel = fuel - UFO_FUEL_USE
		end
		if fuel > 0 and ctrl.up then -- Key UP = Acelerador
			vel.x = vel.x + math.cos(self.object:getyaw()+math.pi/2)*UFO_SPEED
			vel.z = vel.z + math.sin(self.object:getyaw()+math.pi/2)*UFO_SPEED
			fuel = fuel - UFO_FUEL_USE
		else
			vel.x = vel.x*0.99
			vel.z = vel.z*0.99
		end
		if ctrl.down then -- Key DOWN = Freio
			vel.x = vel.x*0.5 --Padrão = 0.9
			vel.z = vel.z*0.5 --Padrão = 0.9
			fuel = fuel - UFO_FUEL_USE
		end
		
		
		if ctrl.aux1 and ctrl.sneak then --Padrao = Ctrl(aux/correr)+Shift(sneak/abaixar)
			--[[
			if self.driver:is_player() then
				--minetest.sound_play("sfx_falha", {object = self.object, gain = 2.0, max_hear_distance = 10}) --toca som "sfx_falha".ogg a distancia de 10 blocos do elicoptero.
				minetest.sound_play("sfx_chat2", {object = self.object, gain = 2.0, max_hear_distance = 10}) --toca som "sfx_chat2".ogg a distancia de 10 blocos do elicoptero.
			end
			
			
			local trunk_formspec = lunovns.ufo:getFormSpecTrunk(self.driver)
			local inv = lunovns.getDetachedInventory(self, self.driver)
			
			print(self.driver:get_player_name().." abriu o porta malas do seu disco-voador.")
			minetest.show_formspec(self.driver:get_player_name(), "frmTrunk", trunk_formspec)

			minetest.register_on_player_receive_fields(function(player, formname, fields)
				if lunovns.check_owner(self, player) and self.driver and self.driver:is_player() and formname == "frmTrunk" then -- This is your form name
					--local inv = lunovns.getDetachedInventory(self, self.driver)
					--print("--------- Player "..player:get_player_name().." submitted fields "..dump(fields))
					if fields.quit then
						print(player:get_player_name().." fechou o porta malas do seu disco-voador.")
						--self.invTrunk[player:get_player_name()] = inv:get_list("main")
					elseif fields.btnDownload == "Descarregar" then
						if not inv:is_empty("main") then
							print(player:get_player_name().." descarregou o porta malas do seu disco-voador.")
							for n,stack in ipairs(inv:get_list("main")) do
								player:get_inventory():add_item("main",stack)
								inv:remove_item("main",stack)
							end
							self.invTrunk[player:get_player_name()] = inv:get_list("main")
						end
					end
				end
				return true --fim do if lunovns.check_owner(self, player) and self.driver and self.driver:is_player() and formname == "frmTrunk" then
			end)			
			]]--
		elseif fuel > 0 and ctrl.jump then
			vel.y = vel.y+UFO_SPEED
			fuel = fuel - UFO_FUEL_USE
		elseif fuel > 0 and ctrl.sneak then
			vel.y = vel.y-UFO_SPEED
			fuel = fuel - UFO_FUEL_USE
		else
			vel.y = vel.y*.9
		end
		
		if vel.x > UFO_MAX_SPEED then vel.x = UFO_MAX_SPEED end
		if vel.x < -UFO_MAX_SPEED then vel.x = -UFO_MAX_SPEED end
		if vel.y > UFO_MAX_SPEED then vel.y = UFO_MAX_SPEED end
		if vel.y < -UFO_MAX_SPEED then vel.y = -UFO_MAX_SPEED end
		if vel.z > UFO_MAX_SPEED then vel.z = UFO_MAX_SPEED end
		if vel.z < -UFO_MAX_SPEED then vel.z = -UFO_MAX_SPEED end
		self.object:setvelocity(vel)

		if ctrl.aux1 then
			local pos = self.object:getpos()
			local t = {{x=2,z=0},{x=-2,z=0},{x=0,z=2},{x=0,z=-2}}
			for _, i in ipairs(t) do
				pos.x = pos.x + i.x; pos.z = pos.z + i.z;
				if minetest.env:get_node(pos).name == "lunovns:furnace" then
					local meta = minetest.env:get_meta(pos)
					if fuel < 100 and meta:get_int("charge") > 0 then
						fuel = fuel + 1
						meta:set_int("charge",meta:get_int("charge")-1)
						meta:set_string("formspec", lunovns.furnace_inactive_formspec
							--.. "label[0,0;Carga: "..meta:get_int("charge")
							.. "label[1.3,0.4; Carga: ".. meta:get_int("charge") .." Volts]"
						)
					end
				end
				pos.x = pos.x - i.x; pos.z = pos.z - i.z;
			end
		end
		--fuel = fuel - UFO_FUEL_USE
	else
		local vel = self.object:getvelocity()
		vel.y = vel.y-0.5
		self.object:setvelocity(vel)
	end
	
	if fuel < 0 then 
		fuel = 0 
		local vel = self.object:getvelocity()
		vel.y = vel.y-0.5
		self.object:setvelocity(vel)
	end
	if fuel > 100 then fuel = 100 end
	if self.fueli ~= math.floor(fuel*8/100) then
		self.fueli = math.floor(fuel*8/100)
		print(self.fueli)
		self.textures = {"ufo_"..self.fueli..".png"}
		self.object:set_properties(self)
	end
	lunovns.set_fuel(self,fuel)
end

function lunovns.ufo:get_staticdata()
	return self.owner_name..";"..tostring(self.fuel)
end

minetest.register_entity("lunovns:ufo", lunovns.ufo)


minetest.register_tool("lunovns:ufo", {
	description = "Disco-Voador",
	inventory_image = "ufos_inventory.png",
	wield_image = "ufos_inventory.png",
	tool_capabilities = {load=0,max_drop_level=0, groupcaps={fleshy={times={}, uses=100, maxlevel=0}}},
	
	on_place = function(itemstack, placer, pointed_thing)
		if pointed_thing.type ~= "node" then
			return
		end
		
		-- Call on_rightclick if the pointed node defines it
		if placer and not placer:get_player_control().sneak then
			local n = minetest.get_node(pointed_thing.under)
			local nn = n.name
			if minetest.registered_nodes[nn] and minetest.registered_nodes[nn].on_rightclick then
				return minetest.registered_nodes[nn].on_rightclick(pointed_thing.under, n, placer, itemstack) or itemstack
			end
		end
		
		lunovns.ufo_from_item(itemstack,placer,pointed_thing)
		return itemstack
	end,
})

minetest.register_craft( {
	output = 'lunovns:ufo',
	recipe = {
		{ "", "default:glass", ""},
		{ "default:mese_crystal_fragment", "", "default:mese_crystal_fragment"},
		{ "default:steelblock", "default:mese", "default:steelblock"},
	},
})
minetest.register_alias("ufo"				, "lunovns:ufo")
minetest.register_alias("ovni"			, "lunovns:ufo")
minetest.register_alias("discovoador"	, "lunovns:ufo")



--[[
-- lunovns box kept for compatibility only
minetest.register_node("lunovns:box", {
	description = "Abastecedor (Discos-Voadores)",
	tiles = {"ufos_box.png"},
	groups = {not_in_creative_inventory=1},
	on_rightclick = function(pos, node, clicker, itemstack)
		meta = minetest.env:get_meta(pos)
		if meta:get_string("owner") == clicker:get_player_name() then
			-- set owner
			lunovns.next_owner = meta:get_string("owner")
			-- restore the fuel inside the node
			lunovns.set_fuel(lunovns.ufo,meta:get_int("fuel"))
			-- add the entity
			e = minetest.env:add_entity(pos, "lunovns:ufo")
			-- remove the node
			minetest.env:remove_node(pos)
			-- reset owner for next ufo
			lunovns.next_owner = ""
		end
	end,
})
minetest.register_alias("box"				, "lunovns:box")
minetest.register_alias("abastecedor"	, "lunovns:box")
]]--

dofile(minetest.get_modpath("lunovns").."/furnace.lua")

